package com.ifinc.common.protocol.i8583.field;

import com.ifinc.common.utils.encode.BcdUtils;
import com.ifinc.common.utils.encode.ByteUtil;
import com.ifinc.common.utils.sec.MacUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * User: luotao
 * Date: 13-11-15
 * Time: 13:41
 */
public class FieldMac extends AbstractField{

    private List<Integer> joinMacFields = new ArrayList<Integer>();

    public FieldMac(Integer ... joinMacInfo) {
        super(8,true);
        for (Integer integer : joinMacInfo) {
            joinMacFields.add(integer);
        }
    }

    public void clearBytes(){
        srcBytes = new byte[]{};
        resBytes = new byte[]{};
        srcValue = "";
    }

    @Override
    public byte[] toByte() {
        if(!i8583Request.isNeedMac()){
            clearBytes();
            return srcBytes;
        }
        List<Byte> byteList = new ArrayList<Byte>();
        Map<Integer, Field> data = i8583Request.getData();
        for (Integer fieldId : joinMacFields) {
            Field field = data.get(fieldId);
            byte[] macData = field.toMacByte();
            byteList.addAll(ByteUtil.byteArray2List(macData));
        }
        byte[] macSrcData = ByteUtil.list2ByteArray(byteList);
        String macData = MacUtils.doMacANSI_x99_asc(i8583Request.getZmk(), i8583Request.getZak(), macSrcData);
        byte[] macBytes = BcdUtils.hex2byte(macData.getBytes());
        resBytes = macBytes;
        srcBytes = macBytes;
        return macBytes;
    }

    @Override
    public byte[] toMacByte() {
        return new byte[0];
    }

    @Override
    public String getFieldType() {
        return VAR;
    }

    @Override
    public boolean isAutoFill() {
        return true;
    }

    @Override
    public int toValue(byte[] data, int index) {
        return 0;
    }
}
